package com.my12306.user.util.auth;

import com.my12306.user.model.po.PUserEntity;
import com.my12306.user.service.PUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author:苏牧夕
 * @Date:2020/5/22 1:21
 * @Version 1.0
 */
@Component
public class OauthUtils {
    @Resource
    private PUserService pUserService;

    /**
     * 获取用户名
     *
     * @return
     */
    public String getUserInfo() {
        PUserEntity principal = getUserPrincipal();
        return principal == null ? null : principal.getUsername();
    }

    /**
     * 获取用户完整的信息
     *
     * @return
     */
    public PUserEntity getUserPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);
        Object principal = authentication.getPrincipal();
        System.out.println("==================>");
        System.out.println("用户信息：" + principal);
        if (principal instanceof PUserEntity) {
            return principal.equals("anonymousUser") ? null : (PUserEntity) principal;
        } else {
            if (principal.equals("anonymousUser")) {
                return null;
            } else {
                return pUserService.queryUserByUsername(principal.toString());
            }
        }
    }

    /**
     * 获取用户id
     *
     * @return
     */
    public Long getUserId() {
        PUserEntity principal = getUserPrincipal();
        return principal == null ? null : principal.getId();
    }
}

